// pages/Comment/CommentDetail/CommentDetail.js
const Controller = require('../../controllers/controllers').controller
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loveIconId: 0, //点击点赞爱心按钮
    inputBottom: 0, //用于输入框能键盘弹出使得布局上移
    content: '', //输入框内容,
    focusInput: false,
    Sponsor: {}, //评论发起人
    ReplyingPersonList: [], //回复人 
    page: 1,
    pageSize: 10,
    lastPage: null,
    options: {}, //别的页面传来的参数
    bodyId: 1, //type == 5使用，表示评论的对象，具体是1是栏目，2是合辑，3是音频的id,当是一级评论则rid = bodyId
    isCheckCollect: null, //检测点赞收藏返回来的id
    rid: '', //关联的id
    toUserId: '',
    title:'评论详情'
  },
  timer: null,
  // 点击评论触发input的focus方法
  focusButn(e) {
    console.log('点击评论触发input的focus方法', e)
    this.setData({
      focusInput: true,
      rid: e.currentTarget.dataset.rid, //评论的id
      toUserId: e.currentTarget.dataset.touserid //用户touserid
    })
  },
  // 输入框聚焦
  foucus(e) {
    var that = this;
    console.log('e.detail.height', e, e.detail.height)
    that.setData({
      inputBottom: e.detail.height
    })
  },
  // 输入框失焦
  blur(e) {
    var that = this;
    that.setData({
      inputBottom: 0
    })
  },
  // 输入框事件
  getInputText(e) {
    var that = this;
    // console.log(e)
    that.setData({
      content: e.detail.value
    })
  },
  // 输入框提交按钮 -> 评论 参数：content type = 4 rid（关联id :评论的对象id）
  submit() {
    var that = this;
    let content = this.data.content;
    let rid = '' // 被评论人的id
    if (this.data.focusInput) {
      rid = this.data.rid; //评论的id
    } else {
      rid = this.data.options.id //页面传来的关联id
    }
    console.log('输入框提交按钮', content, !Boolean(content))
    if (!Boolean(content)) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      })
      return
    }
    Controller.comment({
        content,
        rid, //当前评论的id
        bodyId: that.data.options.bodyId, //关联的音频或栏目或合辑的id
        type: 5, //评论对象的类型，1是栏目，2是合辑，3是音频，4是评论
        bodyType: that.data.options.type, //1是栏目，2是合辑，3是音频，4是达人榜
        toUserId: that.data.toUserId //用户id
      })
      .then(res => {
        console.log('评论发送', res)
        if (res.code == 0) {
          wx.showModal({
            title: '提示',
            content: '评论成功，等待审核中~~',
            showCancel: false
          })
          that.setData({
            content: '',
            focusInput: false,
            toUserId:''
          })
          app.updateScore(8)
        }
      })
    this.setData({
      focusInput: false
    })
  },
  // 当前用户评论发起人-> 参数id（评论id）
  commentDetail() {
    let id = this.data.options.id
    console.log(this.data.options)
    Controller.commentDetail({
        id, //评论id
        token: wx.getStorageSync('logintoken')
      })
      .then(res => {
        console.log('当前用户评论发起人', res)
        if (res.code == 0 && res.data && res.data.baseData) {
          res.data.baseData.select = res.data.baseData.liked == 1 ? true : false
          res.data.baseData.likeNums = res.data.baseData.likeCount
          res.data.baseData.createTime = app.getBeforeTime(res.data.baseData.createTime)
          this.setData({
            Sponsor: res.data.baseData
          })
        }
      })
  },
  // 评论回复人->评论列表 参数page pageSize rid（关联id） type=5
  // type：1是栏目，2是合辑，3是音频，4是达人榜，5是评论
  commentList() {
    let that = this
    let params = {
      page: that.data.page,
      pageSize: that.data.pageSize,
      rid: this.data.options.id, //关联id
      type: 5,
      token: wx.getStorageSync('logintoken')
    }
    Controller.commentList(params)
      .then(res => {
        console.log('评论回复人', res)
        if (res.code == 0 && res.data && res.data.baseData && res.data.baseData.list) {
          res.data.baseData.list.map(item => {
            item.select = item.liked == 1 ? true : false;
            item.likeNums = item.likeCount
            item.createTime = app.getBeforeTime(item.createTime)
          })
          that.setData({
            ReplyingPersonList: that.data.ReplyingPersonList.concat(res.data.baseData.list),
            page: res.data.baseData.pageNumber,
            lastPage: res.data.baseData.lastPage,
            pageSize: res.data.baseData.pageSize,
          })
        }
      })
  },
  // 评论发起人点赞
  async commentOriginatorBtn(e) {
    let Sponsor = this.data.Sponsor;
    let that = this
    Sponsor.select = !Sponsor.select
    Sponsor.likeNums = Sponsor.select ? Sponsor.likeNums + 1 : Sponsor.likeNums - 1
    this.setData({
      Sponsor
    })
    if (this.timer) {
      clearTimeout(this.timer)
    }
    console.log('评论发起人点赞')
    this.timer = setTimeout(() => {
      if (Sponsor.select) {
        that.collectFn(e);
      } else {
        that.delCollectfn(that.data.isCheckCollect, e)
      }
    }, 200)
  },
  // 他人评论点赞
  async OthersBtn(e) {
    console.log('他人评论点赞', e)
    let ReplyingPersonList = this.data.ReplyingPersonList
    let that = this
    let flag = null;
    ReplyingPersonList.map(item => {
      if (item.id == e.currentTarget.dataset.touserid) {
        item.select = item.select ? false : true
        flag = item.select ? false : true
        item.likeNums = flag ? item.likeNums - 1 : item.likeNums + 1
      }
    })
    that.setData({
      ReplyingPersonList
    })
    console.log('flag', flag)
    if (that.timer) {
      clearTimeout(this.timer)
    }
    that.checkCollect(e.currentTarget.dataset.id);
    that.timer = setTimeout(() => {
      if (!flag) {
        that.collectFn(e)
      } else {
        that.delCollectfn(that.data.isCheckCollect, e)
      }
    }, 300)
  },
  // 检测是否点赞收藏
  checkCollect(rid) {
    Controller.checkCollect({
        type: 5,
        rid,
        token: wx.getStorageSync('logintoken')
      })
      .then(res => {
        console.log(res)
        if (res.code == 0) {
          this.setData({
            isCheckCollect: res.data.baseData
          })
        }
      })
  },
  // 点赞方法
  collectFn(e) {
    console.log('点赞方法', e)
    let that = this
    let rid = ''
    let toUserId = ''
    if (e.currentTarget.dataset.id) {
      // 评论列表
      rid = e.currentTarget.dataset.id
      toUserId = e.currentTarget.dataset.id
    } else {
      // 评论发起人
      rid = that.data.options.id
      toUserId = that.data.options.id
    }
    let params = {
      rid, //被点赞的对象评论id
      type: 5,
      bodyId: this.data.options.bodyId, //type == 5使用，表示评论的对象，具体是1是栏目，2是合辑，3是音频的id,当是一级评论则rid = bodyId
      toUserId, //被点赞的评论的主人id //type=5时才使用,
      bodyType: that.data.options.type //主体的类型（音频，合辑，栏目的type）
    }
    Controller.collect(params)
      .then(res => {
        console.log('点赞方法', res)
        if (res.code == 0) {
          wx.showToast({
            title: res.msg,
            duration: 1000
          })
        }
        app.updateScore(9)
      }).catch(err => {
        wx.showToast({
          title: err.data.msg,
          duration: 1000
        })
        return false
      })
    that.checkCollect(rid)
  },
  // 取消收藏
  delCollectfn(rid, e) {
    let that = this
    let id = ''
    if (e.currentTarget.dataset.rid) {
      // 判断是否为评论详情
      id = e.currentTarget.dataset.rid
    } else {
      id = that.data.options.id
    }
    Controller.delCollect({
        ids: rid
      })
      .then(res => {
        console.log('取消收藏', res)
        if (res.code == 0) {
          that.checkCollect(id)
        }
      })
  },
  /**
   * 生命周期函数--监听页面加载
   * 
   * 点赞
   *    rid:被点赞的评论id
   *    type：5 表示评论类型
   *    bodyId：this.data.options.bodyId 主体id（type == 5使用，表示评论的对象，具体是1是栏目，2是合辑，3是音频的id,当是一级评论则rid = bodyId）
   *    toUserId：被点赞的用户id（toUserId）
   *    bodyType：that.data.options.type 主体的类型（音频，合辑，栏目的type）
   */
  onLoad: function (options) {
    console.log('生命周期函数--监听页面加载', options)
    this.setData({
      options, //当前评论的id和bodyId  bodyId(主体的id【音频，合辑，栏目等的】)用于点赞的时候
      rid: options.id
    })
    // 当前用户评论发起人
    this.commentDetail();
    // 评论回复人
    this.commentList();
    this.checkCollect(options.id)
  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.lastPage) {
      this.setData({
        page: this.data.page + 1
      })
      this.commentList();
      console.log('页面上拉触底事件的处理函数')
    }
  },

  onShareAppMessage: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM·评论详情',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },
  onShareTimeline: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM·评论详情',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },
})